package org.andiv.android.esemeser;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;

/**
 * Helper Activity for creating shortcut. It is filtered in AndroidManifest to show in list of activities capable for creating shortcut.
 * When it's called that way it launches MsgChooser in {@link MsgChooser#SHORTCUT} mode and scans for it's result. 
 * When it happens {@link #onActivityResult(int, int, Intent)} is executed and one {@link Intent} is created to actualy execute shortcut (shotcutIntent),
 *  and wrapped in another intent which is representing shortcut with icon and display text (intent)  
 *   
 * @author andrej
 *
 */
public class MsgShortcut extends Activity {
  

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) {
      setupShortcut();
      //finish();
      return;
    }
  }

  /**
   * Launching {@link MsgChooser} in {@link MsgChooser#SHORTCUT} mode ...
   */
  private void setupShortcut() {
    Intent mchoose = new Intent(this, MsgChooser.class);
    mchoose.putExtra(MsgChooser.SMS_ACTION, MsgChooser.SHORTCUT);
    startActivityForResult(mchoose, 34);
  }
  
  /**
   * @see MsgShortcut
   */
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 34 && resultCode == RESULT_OK) {
      Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
      shortcutIntent.setClassName(this, "org.andiv.android.esemeser.MsgChooser");
      int s_id = data.getExtras().getInt(MsgChooser.MSG_ID);
      shortcutIntent.putExtra(MsgChooser.MSG_ID, s_id);
      shortcutIntent.putExtra(MsgChooser.SMS_ACTION, MsgChooser.RUNSHORTCUT);

      // Then, set up the container intent (the response to the caller)

      Intent intent = new Intent();
      intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
      intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, data.getExtras().getString(MsgChooser.MSG_DESC));
      Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
              this,  MsgChooser.getDb().getMsgIcon(s_id, R.drawable.icon));
      intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);

      // Now, return the result to the launcher

      setResult(RESULT_OK, intent);
      finish();
    }
  }
}
